package com.kancy.spring.utils;

import java.io.*;
import java.nio.charset.Charset;

/**
 * FileUtils
 *
 * @author kancy
 * @date 2020/2/18 19:16
 */
public abstract class FileUtils {

    public static String readFileToString(final File file, final Charset encoding) throws IOException {
        return new String(readFileToByteArray(file), encoding);
    }

    public static byte[] readFileToByteArray(final File file) throws IOException {
        InputStream in = new FileInputStream(file);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        IoUtils.copy(in, out);
        return out.toByteArray();
    }

    public static void writeByteArrayToFile(byte[] bytes, final File file) throws IOException {
        ByteArrayInputStream in = new ByteArrayInputStream(bytes);
        FileOutputStream out = new FileOutputStream(file);
        IoUtils.copy(in, out);
    }

    public static File newFile(String filePath) throws IOException {
        File file = new File(filePath);
        if (!(file.exists() && file.isFile())){
            file.getParentFile().mkdirs();
            file.createNewFile();
        }
        return file;
    }

}
